package com.jielin.handling.util;

import java.io.IOException;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

/**
 * 类名称：HttpUtil </br>
 * 创建人：zhanglongdeng@163.com </br>
 * 创建时间：2019年1月2日 下午6:21:58 </br>
 * 类描述：HTTP请求工具类
 */
public class HttpUtil {
	public static final String CHARACTER_ENCODING = "UTF-8";

	public static String sendHttpPostWithJson(String url, String params) {
		return sendHttpForPost(url, params, "application/json");
	}

	public static String sendHttpForPost(String url, String params, String appType) {
		CloseableHttpResponse response = null;
		HttpPost method = new HttpPost(url);
//		StringEntity entity = new StringEntity(params, CHARACTER_ENCODING);// 解决中文乱码问题
//		entity.setContentEncoding(CHARACTER_ENCODING);
//		entity.setContentType(appType);
//		method.setEntity(entity);
		String resData = "";
		try {
			CloseableHttpClient client = HttpClientBuilder.create().build();
			response = client.execute(method);
			resData = EntityUtils.toString(response.getEntity(),CHARACTER_ENCODING);
		} catch (Exception e) {
			throw new RuntimeException("send " + url + " post request is failed. occurs " + e.getLocalizedMessage(), e);
		} finally {
			try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resData;
	}
	
	public static String sendHttpForGet(String url, String params, String appType) {
		CloseableHttpResponse response = null;
		HttpGet method = new HttpGet(url);
//		StringEntity entity = new StringEntity(params, CHARACTER_ENCODING);// 解决中文乱码问题
//		entity.setContentEncoding(CHARACTER_ENCODING);
//		entity.setContentType(appType);
//		method.setEntity(entity);
		String resData = "";
		try {
			CloseableHttpClient client = HttpClientBuilder.create().build();
			response = client.execute(method);
			resData = EntityUtils.toString(response.getEntity(),CHARACTER_ENCODING);
		} catch (Exception e) {
			throw new RuntimeException("send " + url + " post request is failed. occurs " + e.getLocalizedMessage(), e);
		} finally {
			try {
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resData;
	}
	
	public static void main(String[] args) {
	}
}
